import router from "./index";
import useMain from "@/stores/useMain.js";
import {Util,TokenUtil,MessageBox,I18Parse} from "@lowcode/jpaas-base-lib";
import {client_id, getAuthorizeUri, getState,getQueryVariable} from "@/assets/js/loginPublic.js";
import rxAjax from '@/assets/js/ajax.js';
import componentLang from "@/language/lang/impl/layouts/compomentLang";
import routerConfig from "./routerConfig.js";
function hasRouter(obj,url,callback){
    let flag = callback(obj,url);
    if(flag){
        return true;
    }
    if(obj.children && obj.children.length>0){
        for(let i=0;i<obj.children.length;i++){
            let path = obj.children[i].path;
            path = (path.indexOf("/")==0?'':'/') + path;
            flag = hasRouter(obj.children[i],url + path,callback);
            if(flag){
                return true;
            }
        }
    }
    return false;
}
router.beforeEach((to, from, next) => {
    //token
    //token
    const  token=TokenUtil.getToken();
    const store = useMain()
    if(token){
        document.title=  store.getCurAppName();
        if(store.logined){
            next();
            return;
        } else {
            if(!store.appKey){
                if(to.params && to.params.appKey){
                    store.setAppKey(to.params.appKey);
                } else {
                    let paths = to.path.split("/");
                    store.setAppKey(paths[1]);
                }
            }
            store.generateRoutes(() => import( '@/views/MainLayout.vue')).then(routers=>{
                //把已获取到的路由菜单加入到路由表中
                let home = routerConfig.find(item=>item.name === 'home');
                if(home){
                    home.children = [...home.children,...routers];
                    router.addRoute(home);
                }

                let redirect = decodeURIComponent(from.query.redirect || to.path);
                let ary = router.getRoutes();
                let flag = false;
                //回调地址不包含http与https
                if (redirect.startsWith('https://') || redirect.startsWith('http://')) {
                    flag = true;
                }else {
                    for(let idx in ary){
                        let obj = ary[idx];
                        flag = hasRouter(obj,obj.path,(item,url)=>{
                            if(url == redirect || (to.name && obj.name == to.name)){
                                if(obj.meta && obj.meta.menuType == 'R'){
                                    store.setHideArea(true);
                                }else{
                                    store.setHideArea(false);
                                }
                                return true;
                            }
                            return false;
                        })
                        if(flag){
                            break;
                        }
                    }
                }
                if(!flag){
                    MessageBox.warning({title:I18Parse.getI18Val(componentLang,"noAuthGrant","没有权限访问!")});
                    return;
                }
                if (to.path === redirect) {
                    // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                    next({...to, replace: true})
                } else {
                    // 跳转到目的路由
                    location.href=redirect;
                }
            });
        }
    }else {
        let portal = import.meta.env.JPAAS_APP_PORTAL;
        if(portal != 'true') {
            let href = window.location.href ;
            let mainUrl= import.meta.env.JPAAS_MAIN_URL;
            if(!href.includes(mainUrl)){
                window.location.href =  `${mainUrl}?redirect=${href}`
            }
        }else {
            //1.先判断是否有state，如果没有证明第一次进入，则跳转到登录页，否则就是回调页
            let queryState = getQueryVariable('state');
            if (queryState) {
                let localState = sessionStorage.getItem("state");
                //判断state防止CSRF攻击
                if (localState !== queryState) {
                    let state = getState();
                    sessionStorage.setItem("state", state);
                    window.location = getAuthorizeUri(state,client_id,function(authorizeUri,data){
                        sessionStorage.setItem("visitUri", data.redirect_uri);
                        let appKey = sessionStorage.getItem("appKey")
                        window.open(authorizeUri, '_self');
                    });
                } else {
                    //进入回调页面
                    //url获取code
                    let code = getQueryVariable('code');
                    const url = "/api-user/user/org/token/getTokenByCode" + "?code=" + code + '&clientId=' + client_id;
                    rxAjax.get(url).then(resp => {
                        TokenUtil.setToken(resp.access_token);
                        let visitUri = sessionStorage.getItem('visitUri');
                        let appKey = sessionStorage.getItem('appKey');
                        window.location = visitUri + "/" + appKey;
                    }).catch((err) => {
                        console.log(err.response)
                    })
                }
            } else {
                let state = getState();
                sessionStorage.setItem("state", state);
                //构建调整url
                getAuthorizeUri(state,client_id,function(authorizeUri,data){
                    sessionStorage.setItem("visitUri", data.redirect_uri);
                    window.open(authorizeUri, '_self');
                });
            }
        }

    }
})
